<template>
  <div>
    <el-card>
      <!-- template 具名插槽 #分别类型  icon 按钮内小图标 type 按钮类型 -->
      <template #header>
        <el-button icon="ele-Plus" type="primary" @click="changeDialogVisible"
          >添加</el-button
        >
      </template>
      <!-- el-table 组件 data：表格内数据 -->
      <el-table :data="trademarks">
        <!-- el-table-column 设置表格列 label：表格头部分类 index：序号类型 -->
        <el-table-column
          label="序号"
          type="index"
          width="100px"
        ></el-table-column>
        <!-- prop:表单验证 绑定的数据 -->
        <el-table-column label="品牌名称" prop="tmName"></el-table-column>
        <el-table-column label="品牌LOGO">
          <!-- #="{ row column $index }" 匿名插槽拿数据用 row：每一行数据  column：每一列数据 #index ：当前行id -->
          <template #="{ row }">
            <img :src="row.logoUrl" width="100" />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #="{ row }">
            <el-button type="warning" icon="ele-Edit" @click="changeList(row)"
              >修改</el-button
            >
            <el-button type="danger" icon="ele-Delete" @click="delOne(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- el-pagination 组件 --分页 -->

      <el-pagination
        :page-count="pages"
        :current-page="page"
        @current-change="currentChange"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageSize"
        @size-change="sizeChangeHandler"
        layout="prev,pager,next,jumper,->,sizes,total"
      ></el-pagination>

      <el-dialog
        v-model="dialogVisible"
        :title="formData.id ? '编辑品牌 --' + formData.tmName : '添加品牌'"
      >
        <el-form :model="formData" :rules="formDataRules" ref="formRef">
          <el-form-item label="品牌名称" prop="tmName">
            <el-input v-model="formData.tmName"></el-input>
          </el-form-item>
          <el-form-item label="品牌LOGO" prop="logoUrl">
            <el-upload
              class="uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="onSuccessHandler"
              :before-upload="BeforeUnloadHandler"
            >
              <img
                v-if="formData.logoUrl"
                :src="formData.logoUrl"
                class="thumb"
              />
              <el-icon v-else class="uploader-icon"
                ><ele-Plus></ele-Plus
              ></el-icon>

              <template #tip>
                <p>
                  上传的图片必须是{{
                    settings.uploadFileExt.join("、")
                  }}等类型并且大小不能超过 {{ settings.uploadFileLimitSize }} M
                </p>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>

        <template #footer>
          <el-button type="default" @click="cancelSub"> 取消</el-button>
          <el-button type="primary" @click="confirmlSub">确定</el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "ProductTrademark",
});
</script>
<script lang="ts" setup>
import { reactive, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import settings from "@/settings";

import * as apis from "@/api/trademark";

//类型
import type {
  FormRules,
  UploadFile,
  UploadFiles,
  UploadRawFile,
} from "element-plus";

import type { IBaseTrademark } from "@/api/trademark";

// 存储获取到 trademarks 列表
const trademarks = ref<IBaseTrademark[]>([]);
const pages = ref(0);
const page = ref(1);
const pageSize = ref(5);
const dialogVisible = ref(false);
const uploadUrl = `${import.meta.env.VITE_API_URL}/product/upload`;

const formData = ref<
  Partial<Pick<IBaseTrademark, "id">> & Omit<IBaseTrademark, "id">
>({
  tmName: "",
  logoUrl: "",
});

const formDataRules: FormRules = {
  tmName: { required: true, min: 1, message: "品牌名称不能为空" },
  logoUrl: {
    required: true,
    validator(rule: any, value: string, callback) {
      if (value.trim().startsWith("http")) {
        callback();
      } else {
        callback(new Error("上传图片地址不正确"));
      }
    },
  },
};

const formRef = ref();

async function getBaseTrademarkByPage() {
  try {
    const res = await apis.requestBaseTrademarkByPage(
      page.value,
      pageSize.value
    );
    trademarks.value = res.records;
    pages.value = res.pages;
  } catch (e) {}
}

getBaseTrademarkByPage();

function currentChange(v: number) {
  page.value = v;
  getBaseTrademarkByPage();
}

function sizeChangeHandler(v: number) {
  pageSize.value = v;
  getBaseTrademarkByPage();
}

function changeDialogVisible() {
  dialogVisible.value = true;

  formData.value = {
    tmName: "",
    logoUrl: "",
  };

  setTimeout(() => {
    formRef.value.clearValidate();
  });
}

function onSuccessHandler(
  response: { data: string },
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) {
  formData.value.logoUrl = response.data;
}

function BeforeUnloadHandler(rawFile: UploadRawFile) {
  //rawFile 文件数据
  //通过白名单验证文件后缀

  if (!settings.uploadFileExt.includes(rawFile.type.slice(6))) {
    ElMessage.error("图片不符合上传格式");
    return false;
  }
  if (settings.uploadFileLimitSize * 1204 < rawFile.size / 1024) {
    ElMessage.error("上传图片太大 遭不住了");
    return false;
  }
}

function cancelSub() {
  dialogVisible.value = false;
}

async function confirmlSub() {
  const operation = formData.value.id ? "编辑" : "添加";

  try {
    await formRef.value.validate();
    if (!formData.value.id) {
      await apis.requestSaveBaseTrademark(formData.value);
    } else {
      await apis.reqChangeTrademark(formData.value as IBaseTrademark);
    }
    ElMessage.success(`${operation}成功`);
    dialogVisible.value = false;
    getBaseTrademarkByPage();
  } catch (e) {
    ElMessage.error(`${operation}失败`);
  }
}

function changeList(row: IBaseTrademark) {
  // console.log(row, column, $index);

  dialogVisible.value = true;

  formData.value = { ...row };
}

async function delOne(id: number) {
  try {
    await ElMessageBox.confirm("你确定要删除一下？", "提示", {
      type: "warning",
    });
    await apis.reqDelOneTrademark(id);
    ElMessage.success("删除成功");
    getBaseTrademarkByPage();
  } catch (e) {
    ElMessage.error("删除成功");
  }
}
</script>

<style>
.uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.el-icon.uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
<style scoped>
.uploader .thumb {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
